#include "pthreadPool.h"

int exitPipe[2];//退出管道
void handler(int signum);//退出信号

/* 线程池 */
int main(int argc, char *argv[])
{
    // ./server 192.168.21.128 12345 3
    ARGS_CHECK(argc,4);

    pipe(exitPipe);
    if(fork()){
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("Parent is going to exit.\n");
        exit(0);
    }
    close(exitPipe[1]);

    int workNum = atoi(argv[3]);
    threadPool_t threadPool;
    initThreadPool(&threadPool,workNum);
    makeWorker(&threadPool);
    int sockFd = initTcp(argv[1],argv[2]);
    int epfd = epoll_create(1);
    epollAdd(epfd,sockFd);
    epollAdd(epfd,exitPipe[0]);

    struct epoll_event readySet[1024];
    while(1){
        int readyNum = epoll_wait(epfd,readySet,1024,-1);
        for(int i = 0;i < readyNum; ++i){
            //有链接到来的消息就绪队列
            if(readySet[i].data.fd == sockFd){
                int netFd = accept(sockFd,NULL,NULL);
                printf("Client connect.netfd = %d\n",netFd);
                pthread_mutex_lock(&threadPool.mutex);
                printf("【Master】: Do something ! Workers.\n");
                enQueue(&threadPool.taskQueue,netFd);
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }
            //有退出消息到来的就绪队列
            else if(readySet[i].data.fd == exitPipe[0]){
                printf("【Master】: It's time to go.\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.flag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
                for(int j = 0;j < threadPool.tidArr.workerNum;++j){
                    pthread_join(threadPool.tidArr.pthreadTid[j],NULL);
                }
                printf("【Master】: Bye-bye.\n");
                exit(0);
            }
        }
    }
    return 0;
}

void handler(int signum){
    printf("signum = %d\n",signum);
    write(exitPipe[1],"1",1);
}
///* taskQueu.c 单元测试 */
//int main(int argc, char *argv[])
//{
//    ARGS_CHECK(argc,1);
//    taskQueue_t taskQueue;
//    initQueue(&taskQueue);
//    visitQueue(&taskQueue);
//    for(int i = 0; i < 10; ++i){
//        enQueue(&taskQueue,i);
//        visitQueue(&taskQueue);
//    }
//    for(int i = 0; i < 10; ++i){
//        deQueue(&taskQueue);
//        visitQueue(&taskQueue);
//    }
//    return 0;
//}
//
